import java.io.IOException;
import java.rmi.RemoteException;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.discovery.LookupDiscovery;
import net.jini.discovery.DiscoveryListener;
import net.jini.discovery.DiscoveryEvent;
import net.jini.space.JavaSpace;

class JavaSpaceLookup implements DiscoveryListener {
	private ServiceTemplate fServiceTemplate;
	private LookupDiscovery fLookupDisc;
	private JavaSpace fSpace;

	public JavaSpaceLookup() {
		fServiceTemplate = new ServiceTemplate(null, new Class[] { JavaSpace.class }, null);
	}

	public JavaSpace getSpace(String [] groups) throws Exception {
		synchronized (this) {
			if (fLookupDisc == null) {
				try {
					fLookupDisc = new LookupDiscovery(groups);
					fLookupDisc.addDiscoveryListener(this);
				} catch (IOException anIOE) {
					throw new Exception("Error: JavaSpace Not found");
				}
			}
		}
		return waitForJavaSpace();
	}

	public void exit() {
		if (fLookupDisc != null) {
			fLookupDisc.terminate();
		}
	}

	private JavaSpace waitForJavaSpace() {
		while (fSpace == null) {
			Thread.yield();
		}
		return fSpace;
	}

	public void discovered(DiscoveryEvent dEvent) {
		if (fSpace != null) {
			// Allready found the javaspace
			return;
		}

		ServiceRegistrar[] myRegs = dEvent.getRegistrars();
		ServiceRegistrar myReg = myRegs[0];
		try {
			JavaSpace jSpace = (JavaSpace) myReg.lookup(fServiceTemplate);

			if (jSpace != null) {
				if (fSpace == null) {
					fSpace = jSpace;
					//notify();
				}
				return;
			}
		} catch (RemoteException re) {

		}
	}

	// Called when javaspace service is Toredown
	public void discarded(DiscoveryEvent anEvent) {
	}
}